<?php

namespace Admin;

/**
 * 增加管理员
 */
class AdminAddFormModel extends \Forms\FormBase
{
    /**
     * 设置所有的字段
     */
    protected $_fields = array(
        'admin_name' => array(
            'label' => 'admin_name',
            'name' => 'admin_name',
            'require' => true,
            'message' => "Username is required",
            'validate' => array(
                array("type" => "string", "min" => "1", "msg" => "Username is error")
            ),
        ),
        'admin_password' => array(
            'label' => 'admin_password',
            'name' => 'admin_password',
            'require' => true,
            'message' => "Password is required",
            'validate' => array(
                array("type" => "string", "min" => "1", "msg" => "password is error")
            ),
        ),
        'admin_email' => array(
            'label' => 'admin_email',
            'name' => 'admin_email',
            'require' => true,
            'message' => "Email is required",
            'validate' => array(
                array("type" => "string", "min" => "1", "max" => "100", "msg" => "email is error")
            ),
        ),
        'status' => array(
            'label' => 'status',
            'name' => 'status',
            'require' => true,
            'validate' => array(
                array("type" => "int", "min" => "1", "max" => "2", "msg" => "status is error")
            ),
        ),
    );

    /**
     * 校验密码
     *
     * @return boolean
     */
    public function validateAdminPassword()
    {
        $adminPassword = $this->getFieldValue('admin_password');
        $options = array('value' => $adminPassword, 'min' => 6, 'max' => 16);
        if (!$this->_validateLength($options)) {
            return $this->setFieldMessage('admin_password', 'password is incorrect');
        }
        if (preg_match("/[\x{4e00}-\x{9fa5}]+/u", $adminPassword)) {
            return $this->setFieldMessage('admin_password', 'password is incorrect');
        }
        return true;
    }

    /**
     * 校验邮箱格式
     *
     * @return boolean
     */
    public function validateAdminEmail()
    {
        $adminEmail = $this->getFieldValue('admin_email');
        if (!preg_match("/^[a-zA-Z0-9][a-zA-Z0-9._-]*\@[a-zA-Z0-9]+\.[a-zA-Z0-9\.]+$/A", $adminEmail)) {
            return $this->setFieldMessage('admin_email', 'admin email is incorrect');
        }
        if (!filter_var($adminEmail, FILTER_VALIDATE_EMAIL)) {
            $this->setFieldMessage('admin_email', 'admin email is incorrect');
            return false;
        }
        return true;
    }

}
